package cn.wu.org.controller;

import cn.wu.org.basic.utils.PageList;
import cn.wu.org.basic.utils.Result;
import cn.wu.org.domain.Department;
import cn.wu.org.query.DepartmentQuery;
import cn.wu.org.service.IDepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(value = "部门的API",description="部门相关的功能")
@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService iDepartmentService;

    //根据id查询数据
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Department findById(@ApiParam(value="ID属性",required = true) @PathVariable("id") Long id){

       return iDepartmentService.findById(id);
    }

    //查询所有
    @GetMapping
    public List<Department> findAll(){
        return iDepartmentService.findAll();
    }

    //添加或者修改
    @PutMapping
    public Result addOrUpdate(@RequestBody Department department){
        //如果id为空 就是添加
        try {
            if(department.getId()==null){
                iDepartmentService.add(department);
            }else {//否则就是修改
                iDepartmentService.update(department);
            }
            //将成功的结果返回给前端
            return Result.a().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        //返回失败的结果
        return Result.a().fail();

    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id){

        try {
            iDepartmentService.delete(id);
            return Result.a().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.a().fail();

    }

    //分页
    @PostMapping
    public PageList<Department> queryAll(@RequestBody DepartmentQuery query){
        return iDepartmentService.queryAll(query);
    }
}
